package io.bluefw.microapp.auth.bundle;

import java.util.Collection;
import java.util.HashSet;

import javax.sql.DataSource;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.realm.jdbc.JdbcRealm.SaltStyle;

import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;

public abstract class BlueAuthBundle<T> extends ShiroBundle<T>  {
	public static int HashIterations = 100;
	protected abstract DataSource getDataSource(T configuration, Environment environment);
	
    @Override
    public void initialize(Bootstrap<?> bootstrap) {
    }
    
	@Override
    protected Collection<Realm> createRealms(T configuration, Environment environment) {
        JdbcRealm realm = new JdbcRealm();
        realm.setDataSource(getDataSource(configuration, environment));
        realm.setSaltStyle(SaltStyle.COLUMN);
        realm.setAuthenticationQuery("select password, salt from AUT_Account where name = ?");
        realm.setUserRolesQuery("select r.name from AUT_Role as r, AUT_Account_Role as a_r, AUT_Account as a where r.id = a_r.role_id and a.id = a_r.account_id and a.id = ?");
        realm.setPermissionsQuery("select r_p.permission_id from AUT_Role_Permission as r_p, AUT_Role as r where r_p.role_id = r.id and roles.role = ?");
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(Sha512Hash.ALGORITHM_NAME);
        matcher.setHashIterations(HashIterations);
        realm.setCredentialsMatcher(matcher);
        Collection<Realm> realms = new HashSet<Realm>();
        realms.add(realm);
        return realms;
    };
}
